package com.jingxuan.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;
import java.util.List;

/**
 * CORS跨域配置
 */
@Configuration
public class CorsConfig {

    @Value("${cors.allowed-origins:http://localhost:5173,http://127.0.0.1:5173}")
    private List<String> allowedOrigins;

    @Value("${cors.allowed-methods:GET,POST,PUT,DELETE,OPTIONS}")
    private List<String> allowedMethods;

    @Value("${cors.allowed-headers:*}")
    private List<String> allowedHeaders;

    @Value("${cors.exposed-headers:Authorization}")
    private List<String> exposedHeaders;

    @Value("${cors.allow-credentials:true}")
    private boolean allowCredentials;

    @Value("${cors.max-age:3600}")
    private long maxAge;

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        
        // 设置允许的源 - 使用模式匹配以支持带端口号的请求
        List<String> allowedOriginPatterns = allowedOrigins.stream()
                .map(origin -> origin.replace("http://", "http://*")
                        .replace("https://", "https://*"))
                .toList();
        config.setAllowedOriginPatterns(allowedOriginPatterns);
        // 同时保留原始配置
        config.setAllowedOrigins(allowedOrigins);
        
        // 设置允许的HTTP方法
        config.setAllowedMethods(allowedMethods);
        
        // 设置允许的头信息
        // 当allowCredentials为true时，不能使用通配符*
        if (allowedHeaders.contains("*")) {
            config.setAllowedHeaders(Arrays.asList(
                "Authorization",
                "Content-Type",
                "X-Requested-With",
                "Accept",
                "Origin",
                "Access-Control-Request-Method",
                "Access-Control-Request-Headers"
            ));
        } else {
            config.setAllowedHeaders(allowedHeaders);
        }
        
        // 设置暴露的头信息
        config.setExposedHeaders(exposedHeaders);
        
        // 是否允许发送Cookie
        config.setAllowCredentials(allowCredentials);
        
        // 预检请求的缓存时间
        config.setMaxAge(maxAge);
        
        // 应用配置到所有路径
        source.registerCorsConfiguration("/**", config);
        
        return new CorsFilter(source);
    }
}